import {useEffect, useState} from "react";
import {createNotification, getCurrentTabDomain, getterCookie, settingCookie} from "../utils/cookieUtils.ts";

export default function MainLayout(){
    const [cookie,setCookie]=useState("")
    const [placeholder,setPlaceholder]=useState("请输入Cookie")
    const readCookie=async () => {
        const toJsonFormat = await getterCookie()
        navigator.clipboard.writeText(JSON.stringify(toJsonFormat)).then(() => {
            createNotification(`Cookie复制成功：${toJsonFormat.length}个cookie`)
        })
    }
    const copyCookie=async () => {
        await readCookie()
    }
    const handleCookie=async (cookies: any) => {
        try {
            const cookieList = JSON.parse(cookies)
            const targetUrl=document.getElementById("targetUrl") as HTMLInputElement
            let herf=""
            if (targetUrl) {
                herf=targetUrl.value
            }
            settingCookie(cookieList,herf).then(() => {
                createNotification(`Cookie导入成功,页面马上刷新`).then(() => {
                    // setTimeout(()=>{
                    //     // location.reload()
                    // },2000)
                })
            })
        } catch (e) {
            console.log("error：", e)
            await createNotification(`导入的Cookie格式有误`)
        }
    }
    const writeCookie=async () => {
        await handleCookie(cookie)
    }
    const cookieToJson=async ()=>{
        try{
            JSON.parse(cookie)
            setCookie("")
            setPlaceholder("请输入正确的cookie")
        }catch(e){
            //如果是error，则说明是字符串
            const domain=await getCurrentTabDomain()
            const ck=parseCookies(cookie,domain)
            setCookie(JSON.stringify(ck))
        }
    }
    const parseCookies=(cookieString: string,domain:string)=> {
        const cookiesArray = cookieString.split('; ');
        return cookiesArray.map(item=>{
            const [key, value] = item.split('=');
            return {
                name:key,
                value:value,
                domain:domain
            }
        })
    }
    useEffect(()=>{
        getterCookie().then((res)=>{
            const ck = JSON.stringify(res);
            return setCookie(ck);
        })
    },[])
    return(
        <>
            <div className='w-[600px] p-2 h-80 bg-gray-800 text-cyan-100 flex flex-col'>
                <h1 className='p-1 text-center text-xl'>Cookie处理器</h1>
                <div
                    className="w-full border flex-1 flex flex-col justify-center items-center rounded">
                        <textarea id="cookie"
                                  value={cookie}
                                  onChange={(e) => setCookie(e.target.value)}
                                  className="w-full flex-1 text-sm text-gray-900 bg-white resize-none focus:ring-0 p-2"
                                  placeholder={placeholder}
                        ></textarea>
                    <div className="flex w-full justify-center py-1 space-x-2">
                    <input type="text" name="url" id="targetUrl" className="w-2/3 py-1" placeholder="请输入网页"/>
                    </div>
                    <div className="flex w-full justify-evenly py-1 space-x-2">
                        <button type="submit"
                                className="inline-flex items-center py-2 px-4 text-xs font-medium text-center bg-gray-900 text-cyan-100 rounded-lg focus:ring-4 focus:ring-blue-200 dark:focus:ring-blue-900 hover:bg-blue-800"
                                onClick={()=>setCookie("")}
                        >
                            清除
                        </button>
                        <button type="submit"
                                className="inline-flex items-center py-2 px-4 text-xs font-medium text-center bg-gray-900 text-cyan-100 rounded-lg focus:ring-4 focus:ring-blue-200 dark:focus:ring-blue-900 hover:bg-blue-800"
                                onClick={copyCookie}
                        >
                            复制Cookie
                        </button>
                        <button type="submit"
                                className="inline-flex items-center py-2 px-4 text-xs font-medium text-center bg-gray-900 text-cyan-100 rounded-lg focus:ring-4 focus:ring-blue-200 dark:focus:ring-blue-900 hover:bg-blue-800"
                                onClick={writeCookie}
                        >
                            设置Cookie
                        </button>
                        <button type="submit"
                                className="inline-flex items-center py-2 px-4 text-xs font-medium text-center bg-gray-900 text-cyan-100 rounded-lg focus:ring-4 focus:ring-blue-200 dark:focus:ring-blue-900 hover:bg-blue-800"
                                onClick={cookieToJson}
                        >
                            Cookie转Json
                        </button>
                    </div>
                </div>
            </div>
        </>
    )
}
